## R-script to assess balance using a propensity score matching technique with two treatment arms

# Call for all packages needed in this estimation
my_packages <- c("twang", "survey", "haven", "vcd", "jtools", "foreign",
                 "jstable", "labelled", "lme4", "janitor", "knitr")
lapply(my_packages, require, character.only = TRUE) 

# Set working directories for multiple script users
paths = c("C:/Users/susanaot/OneDrive - Inter-American Development Bank Group/SUSANAOT/5_BAElige/", 
          "C:/Users/martina/Inter-American Development Bank Group/Otalvaro Ramirez, Susana - 5_BAElige", 
          "C://Some/other/path")
names(paths) = c("SUSANAOT", "martina", "carlossc")
setwd(paths[Sys.info()[7]])

# Upload data set and identify it as the working dataset
d <- as.data.frame(read_dta("data/baelige1.dta"))

# Minor cleaning
d$Treat <- as.factor(d$Treatment)
var_label(d$zo_Gov_Trustworthy) <- "Normalized"
var_label(d$STD_Trustworthy) <- "Standardized"

# Set a seed (the balance is achieved in a repeated fashion)
set.seed(1)

#Treatment conditions are: Control, Treatment 1 (General Info), Treatment 2 (City)
mnps.d <- mnps(Treat ~ gender + age + Secondary + College + employed + unemployed + ABC1_nse + HasCC + HasInt + HasMed + HasCar + Gov_Q_C + know_baew1 + know_baew2 + know_baew3 + know_baew4 + TrustOthers_D + CollAction_D + Cit_Part_D + Inc_Reg_Burden + duration,
               data = d,
               estimand = "ATE",
               verbose = FALSE,
               stop.method = c("es.mean","ks.mean"),
               n.trees = 5000)
# save the weights
d$w_es <- get.weights(mnps.d, stop.method = "es.mean")
d$w_ks <- get.weights(mnps.d, stop.method = "ks.mean")

path_dta <- paste0(paths[Sys.info()[7]],"/replication/data/data.dta")
write_dta(d, path_dta)

END_OF_R